<template>
  <div class="app-container">
    <el-container>
      <el-aside class="full-height" width="500px">
        <div class="tip d-flex">
          <el-select v-model="status" clearable filterable placeholder="状态">
            <el-option
              v-for="(item, index) in statuses"
              :key="index"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-button
            class="ml12"
            icon="el-icon-plus"
            type="primary"
            @click="handleEdit"
          >
            新增
          </el-button>
          <el-button
            class="ml12"
            icon="el-icon-s-tools"
            type="default"
            @click="handleCell"
          >
            分区设置
          </el-button>
          <el-button
            class="ml12"
            icon="el-icon-refresh"
            type="success"
            @click="getPlans"
          >
            刷新
          </el-button>
        </div>
        <div class="h12"></div>
        <el-table
          :data="plansFilter"
          stripe
          style="width: 100%"
          @row-click="handleDetail"
        >
          <el-table-column
            align="center"
            label="日期"
            prop="val"
            show-overflow-tooltip
            width="160"
          />
          <el-table-column
            align="center"
            label="名称"
            prop="name"
            show-overflow-tooltip
          />
          <el-table-column align="center" label="状态" prop="status">
            <template #default="{ row }">
              <el-tag :type="getStatus(row, 'type')">
                {{ getStatus(row, 'label') }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" prop="act" width="150">
            <template #default="{ row }">
              <el-button
                circle
                icon="el-icon-document-copy"
                size="mini"
                title="复制计划"
                type="success"
                @click.stop="handleCopy(row)"
              />
              <el-button
                circle
                icon="el-icon-minus"
                size="mini"
                title="取消计划"
                type="primary"
                @click.stop="handleCancel(row)"
              />
              <el-button
                circle
                icon="el-icon-delete"
                size="mini"
                title="删除计划"
                type="danger"
                @click.stop="handleDelete(row)"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-aside>
      <el-main
        v-loading="loading"
        class="full-height pt0 pb0"
        style="
          position: relative;
          padding-top: 0;
          margin-left: 12px;
          box-shadow: -10px 0 6px -10px rgba(76, 73, 73, 0.3);
        "
      >
        <l-map :center="center" :options="options" :zoom="zoom">
          <l-tile-layer
            v-for="(item, index) in urls"
            :key="index"
            :url="item"
          />
          <l-circle
            v-for="(circle, index) in circles"
            :key="`circle${index}`"
            :color="circle.color"
            :fill-color="circle.color"
            :lat-lng="circle.center"
            :opacity="0"
            :radius="circle.radius"
          />

          <l-polyline
            v-for="(item, index) in latlngs"
            :key="`polyline${index}`"
            :lat-lngs="item"
          />
          <l-marker
            v-for="(item, index) in devicesFilter"
            :key="`device${index}`"
            :icon="getIcon(item)"
            :lat-lng="[item.lat, item.lng]"
            :title="item.name"
            @click="showDevice(item)"
          >
            <l-tooltip :options="markerOptions">
              <div>
                {{ item.name }}
              </div>
            </l-tooltip>
          </l-marker>
        </l-map>
        <div
          v-if="form.id"
          style="
            position: absolute;
            top: 24px;
            z-index: 999;
            width: 90%;
            margin: 12px 5%;
          "
        >
          <el-descriptions
            border
            :column="2"
            content-class-name="contentClass"
            label-class-name="labelClass"
          >
            <el-descriptions-item label="计划名称">
              {{ form.name }}
            </el-descriptions-item>
            <el-descriptions-item label="执行时间">
              {{ form.val }}
            </el-descriptions-item>
            <el-descriptions-item label="行进方向">
              <span class="font-bold color-success font16">
                {{ form.direction === 1 ? '正向' : '反向' }}
              </span>
            </el-descriptions-item>
            <el-descriptions-item label="执行状态">
              <el-tag :type="statusObj[form.status].type">
                {{ statusObj[form.status].label }}
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </el-main>
    </el-container>
    <edit ref="edit" @getPlans="getPlans" />
    <el-dialog
      append-to-body
      title="手动分区设置"
      :visible.sync="dialogVisible"
      width="800px"
    >
      <el-table
        border
        :data="cellsFormater"
        row-key="id"
        style="width: 100%; margin-bottom: 20px"
      >
        <el-table-column align="left" label="分区" prop="name" width="128" />
        <el-table-column align="center" label="编号" prop="name" width="80">
          <template #default="{ row }">
            <span v-if="row.children">{{ row.id }}</span>
            <span v-else>{{ row.idx }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="喷头范围" prop="name">
          <template #default="{ row }">
            <div v-if="row.pid" style="display: flex; align-items: center">
              <el-input
                v-model="row.spstart"
                placeholder="起始喷头"
                size="small"
              />
              <span style="padding: 0 8px">~</span>
              <el-input
                v-model="row.spend"
                placeholder="终止喷头"
                size="small"
              />
            </div>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="角度范围（度）" prop="address">
          <template #default="{ row }">
            <div v-if="row.children" style="display: flex; align-items: center">
              <el-input
                v-model="row.argstart"
                placeholder="起始角度"
                size="small"
                @change="changeRow(row, 'argstart')"
              />
              <span style="padding: 0 8px">~</span>
              <el-input
                v-model="row.argend"
                placeholder="终止角度"
                size="small"
                @change="changeRow(row, 'argend')"
              />
            </div>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="颜色" prop="address" width="80">
          <template #default="{ row }">
            <el-color-picker
              v-model="row.color"
              :disabled="Boolean(row.children)"
              show-alpha
            />
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" prop="address" width="100">
          <template #header>
            <el-link icon="el-icon-plus" type="primary" @click="addCell(0)">
              添加
            </el-link>
          </template>
          <template #default="{ row, $index }">
            <el-button
              circle
              :disabled="row.pid > 0"
              icon="el-icon-plus"
              size="mini"
              type="primary"
              @click="addCell(row)"
            />
            <el-button
              circle
              icon="el-icon-delete"
              size="mini"
              type="danger"
              @click="removeCell(row, $index)"
            />
          </template>
        </el-table-column>
      </el-table>
      <el-button icon="el-icon-document" type="primary" @click="cellSubmit">
        提交
      </el-button>
    </el-dialog>
    <el-dialog
      v-drag
      :title="deviceTitle"
      :visible.sync="deviceVisible"
      width="1000px"
    >
      <span v-if="currentDevice" slot="title" class="device-header">
        <el-image
          class="device-image"
          :fit="fit"
          :src="getDeviceImage(currentDevice)"
        />
        {{ currentDevice.name + ' —— ' + currentDevice.serialno }}
      </span>
      <div style="height: 640px; overflow-y: scroll"><pg /></div>
    </el-dialog>
  </div>
</template>

<script>
  import { convertArr2Obj, formatCells } from '@/utils'
  import { cells, map, dclassCodeMap } from '@/utils/constant'
  import { plans, cancelPlan, delPlan, getCell, setCell } from '@/api/device'
  import Edit from '../components/Edit'
  import Pg from '@/components/Device/Pg'
  import { getDeviceImage } from '@/utils/device'
  import { mapGetters } from 'vuex'
  import * as turf from '@turf/turf'
  export default {
    components: {
      Edit,
      Pg,
    },
    data() {
      return {
        fit: 'fill',
        serialno: '0110.0007.2027000724',
        deviceTitle: '',
        deviceVisible: false,
        currentDevice: null,
        activeName: 'first',
        loading: false,
        status: '',
        dialogVisible: false,
        form: {},
        cellsFormater: [],
        statuses: [
          { label: '待执行', value: 1, type: 'info' },
          { label: '执行中', value: 2, type: 'primary' },
          { label: '已完成', value: 3, type: 'success' },
          { label: '已取消', value: 4, type: 'danger' },
        ],
        plans: [],
        zoom: 17,
        center: map.center,
        options: map.options,
        urls: map.mapTypes[map.initType],
        markerOptions: {
          permanent: true,
          interactive: false,
          direction: 'bottom',
          offset: [0, 8],
          className: 'anim-tooltip',
        },
        circles: [
          {
            serialno: '0110.0007.2027000724',
            name: '大曹庄农场喷灌机-0724',
            radius: 150,
            center: [37.467294, 114.913504],
            color: `rgba(248, 9, 9, 1)`,
            lat: 37.467294,
            lng: 114.913504,
            latlngs: [
              [37.467294, 114.913504],
              [37.46771532274502, 114.91188941023749],
            ],
          },
        ],
      }
    },
    computed: {
      ...mapGetters(['devices']),
      devicesFilter() {
        const res = this.devices.filter((val) => {
          return +val.product_type === dclassCodeMap.pg && val.map_show > 0
        })

        return res
      },
      latlngs() {
        const sprinklers =
          this.devices.filter((val) => {
            return +val.product_type === +dclassCodeMap.pg
          }) || []
        const res = []
        sprinklers.forEach((item) => {
          const startPos = [+item.lng, +item.lat]
          const radius = +item.settings.radius / 1000
          let angle = 0
          if (item.states.Angle !== undefined) {
            angle = +item.states.Angle
          }
          if (item.states.REG_HMI_GPS !== undefined) {
            angle = +item.states.REG_HMI_GPS
          }
          const endPos = this.getPoint(startPos, radius, angle)

          res.push([
            [startPos[1], startPos[0]],
            [endPos[1], endPos[0]],
          ])
        })
        return res
      },
      cellsFormat() {
        let res = []
        cells.forEach((item) => {
          const { id, idx, name } = item
          res.push({ id, idx, name, p: 60, v: 100, d: 50, endGun: 1 })
        })
        return res
      },
      plansFilter() {
        if (this.status !== '') {
          return this.plans.filter((val) => {
            return +val.status === this.status
          })
        }
        return this.plans
      },
      statusObj() {
        return convertArr2Obj(this.statuses, 'value')
      },
    },
    created() {
      this.getPlans()
    },
    methods: {
      async getCell() {
        const { data } = await getCell(this.serialno)
        this.cellsSprinkler = data
        this.cellsFormater = formatCells(this.cellsSprinkler)
      },
      getDeviceImage(device) {
        return getDeviceImage(device)
      },
      showDevice(currentDevice) {
        this.currentDevice = currentDevice
        this.$store.commit('device/SET_CURRENT_DEVICE', currentDevice)
        this.$store.commit('device/SET_CURRENT_DEVICE_SHOW', true)
        this.serialno = currentDevice.serialno
        this.deviceTitle = currentDevice.name
        this.deviceVisible = true
      },
      getPoint(startPos, distance, bearing) {
        const point = turf.point(startPos)
        const destination = turf.destination(point, distance, bearing)

        return destination.geometry.coordinates
      },
      getIcon(item) {
        // eslint-disable-next-line no-undef
        return L.icon({
          iconSize: [28, 28],
          iconUrl: getDeviceImage(item),
        })
      },
      cancelPlan(id) {
        this.$baseConfirm('确定取消？', null, async () => {
          const { msg } = await cancelPlan(id)
          this.$baseMessage(msg, 'success', 'vab-hey-message-success')
        })
      },
      delPlan(id) {
        this.$baseConfirm('确定取消？', null, async () => {
          const { msg } = await delPlan(id)
          this.$baseMessage(msg, 'success', 'vab-hey-message-success')
        })
      },
      async getPlans() {
        const { data } = await plans(this.serialno, { manual_plan: 1 })
        this.plans = data
        this.form = data[0] || {}
      },
      getStatus(row, field) {
        const statusObj = convertArr2Obj(this.statuses, 'value')
        return statusObj[row.status][field]
      },
      handleCopy(row) {
        row.manual_plan = 1
        this.form = row
        this.$refs.edit.show(row)
      },
      handleCancel(row) {
        this.$baseConfirm('确定取消？', null, async () => {
          const { msg } = await cancelPlan(row.id)
          this.$baseMessage(msg, 'success', 'vab-hey-message-success')
          this.getPlans()
        })
      },
      handleDetail(row) {
        this.loading = true
        setTimeout(() => {
          this.form = row
          this.loading = false
        }, 2000)
      },
      handleDelete(row) {
        this.$baseConfirm('确定删除？', null, async () => {
          const { msg } = await delPlan(row.id)
          this.$baseMessage(msg, 'success', 'vab-hey-message-success')
          this.getPlans()
        })
      },
      handleEdit(row) {
        this.$refs.edit.show(row)
      },
      handleCell() {
        this.getCell()
        this.dialogVisible = true
      },
      async cellSubmit() {
        const cells = this.formatSubmitData(this.cellsFormater)
        console.log(this.serialno, cells)
        const { msg } = await setCell(this.serialno, cells)
        this.$baseMessage(msg, 'success', 'vab-hey-message-success')
      },
      formatSubmitData(cells) {
        const cellsClone = JSON.parse(JSON.stringify(cells))
        let result = []
        cellsClone.forEach((item) => {
          item.children.map((val) => {
            val.id = val.pid
            val.name = val.id + '-' + val.idx
            val.argstart = item.argstart
            val.argend = item.argend
            Object.assign(val, { serialno: this.serialno })
            delete val.pid
            delete val.radius
          })
          result = result.concat(item.children)
        })
        return result
      },
      addCell(pid) {
        if (pid === 0) {
          const id = this.cellsFormater.length + 1
          const item = {
            id: id,
            name: '管理区' + id,
            children: [
              {
                idx: 1,
                id: id + '' + 1,
                pid: id,
                name: '小分区1',
              },
            ],
          }
          this.cellsFormater.push(item)
        } else {
          const idx = pid.children.length + 1
          pid.children.push({
            idx: idx,
            id: pid.id + '' + idx,
            pid: pid.id,
            name: '小分区' + idx,
          })
        }
      },
      removeCell(row, index) {
        if (row.children) {
          this.cellsFormater.splice(index, 1)
        } else {
          const parent = this.cellsFormater.filter(function (val) {
            return val.id === row.pid
          })[0]
          const cindex = parent.children.findIndex((value) => {
            return value.idx === row.idx
          })
          parent.children.splice(cindex, 1)
        }
      },
      changeRow(row, field) {
        row.children.map((val) => {
          val[field] = row[field]
        })
      },
    },
  }
</script>

<style lang="scss" scoped>
  .content {
    height: 720px;
    line-height: 720px;
    text-align: center;
  }
  .anim-tooltip {
    padding-top: 0;
    font-size: 12px;
    color: #fff;
    background: none;
    border: none;
    box-shadow: none;
    transform: scale(0.8);
  }
  .anim-tooltip:before {
    border-bottom-color: rgba(0, 0, 0, 0);
  }
  .device-header {
    display: flex;
    align-items: center;
    font-size: 16px;
  }
  .device-image {
    width: 32px;
    height: 32px;
    margin-right: 8px;
  }
</style>
